package com.yonyou.mm.connector;

import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 发起请求与获取AccessToken凭证类
 * 
 * @date 2016年8月1日 上午10:48:48
 * @author wangjwm
 *
 */
public class ConnectService {

	/**
	 * 发起HTTP/HTTPS请求并获取结果
	 * 
	 * @param requestURL
	 *            请求地址
	 * @param RequestMethod
	 *            请求方式（GRT/POST）
	 * @param RequestMsg
	 *            提交的数据
	 * @return JSONObject 返回结果
	 */
	public static JSONObject HttpRequest(String requestURL, String RequestMethod, String RequestMsg) {
		JSONObject obj = new JSONObject();
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		try {
			url = new URL(requestURL);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(RequestMethod);
			if (RequestMsg != null) {
				OutputStream out = connection.getOutputStream();
				out.write(RequestMsg.getBytes("utf-8"));
				out.close();
			}
			// 流处理（response）
			InputStream input = connection.getInputStream();
			InputStreamReader inputReader = new InputStreamReader(input, "utf-8");
			BufferedReader reader = new BufferedReader(inputReader);
			String line;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			// 释放资源
			reader.close();
			inputReader.close();
			input.close();
			connection.disconnect();
			String inputMsg = buffer.toString();
			obj = JSONObject.fromObject(inputMsg);
		} catch (IOException e) {

		}
		return obj;
	}




}
